package com.xtourms.server;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.xtourms.client.rm.ticket.TicketManagerService;
import com.xtourms.server.db.City;
import com.xtourms.server.db.Ticket;
import com.xtourms.server.db.Ticketstatus;
import com.xtourms.server.db.Worker;
import com.xtourms.server.db.core.DBOper;
import com.xtourms.shared.field.TicketField;

@SuppressWarnings("serial")
public class TicketManagerServiceImpl extends RemoteServiceServlet implements TicketManagerService {

	@Override
	public String cOrMTicket(String ticketInfo) {
		String ret = null;
		Session session = DBOper.openSession();
		Transaction t = session.beginTransaction();
		try {
			t.begin();
			
			Ticket ticket = null;
			JSONObject ticketObj = new JSONObject(ticketInfo);
			int hId = ticketObj.optInt(TicketField.TICKET_ID);
			if (0 != hId) {
				ticket = (Ticket)session.load(Ticket.class, Integer.valueOf(hId));
			}else{
				ticket = new Ticket();
			}
			
			fillTicket(ticket, ticketObj);
			
			session.save(ticket);
			t.commit();
			ret = toJSONTicket(ticket, session).toString();
			session.close();
		} catch (JSONException e) {
			t.rollback();
		}
		return ret;
	}
	
	@Override
	public String cOrMStatus(String statusInfo) {
		String ret = null;
		Session session = DBOper.openSession();
		Transaction t = session.beginTransaction();
		try {
			t.begin();
			
			Ticketstatus status = null;
			JSONObject statusObj = new JSONObject(statusInfo);
			int hId = statusObj.optInt(TicketField.STATUS_ID);
			if (0 != hId) {
				status = (Ticketstatus)session.load(Ticketstatus.class, Integer.valueOf(hId));
			}else{
				status = new Ticketstatus();
			}
			
			fillStatus(status, statusObj, session);
			
			session.save(status);
			t.commit();
			ret = toJSONStatus(status).toString();
			session.close();
		} catch (Exception e) {
			t.rollback();
		}
		return ret;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String queryStatus(String condition) {
		String hql = "from Ticketstatus ts";
		try {
			JSONObject condObj = new JSONObject(condition);
			int ticketId = condObj.optInt(TicketField.TICKET_ID);
			hql += " where ts.ticket=" + ticketId;
		} catch (JSONException e1) {
		}
		Session s = DBOper.openSession();
		Transaction t = s.beginTransaction();
		t.begin();
		Query query = s.createQuery(hql);
		List<Ticketstatus> statusList = query.list();
		Iterator<Ticketstatus> statusIter = statusList.iterator();
		JSONArray ret = new JSONArray();
		while (statusIter.hasNext()) {
			Ticketstatus status = statusIter.next();
			try {
				JSONObject statusObj = toJSONStatus(status);
				ret.put(statusObj);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		s.close();
		return ret.toString();
	}

	@SuppressWarnings("unchecked")
	@Override
	public String queryTicket(String condition) {
		String hql = "from Ticket ticket";
		try {
			JSONObject condObj = new JSONObject(condition);
			int cityId = condObj.optInt(TicketField.TICKET_CITY_ID);
			hql += " where ticket.ticketCity=" + cityId;
			String ticketName = condObj.optString(TicketField.TICKET_NAME);
			if (!ticketName.isEmpty()) {
				hql += " and ticket.ticketName like '%" + ticketName + "%'";
			}
			String add = condObj.optString(TicketField.TICKET_ADD);
			if (!add.isEmpty()) {
				hql += " and ticket.ticketAdd like '%" + add + "%'";
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
		}

		Session s = DBOper.openSession();
		Transaction t = s.beginTransaction();
		try{
			t.begin();
			Query query = s.createQuery(hql);
			//TODO:分页
			query.setFirstResult(0);
			query.setMaxResults(20);
			List<Ticket> ticketList = query.list();
			
			Iterator<Ticket> ticketIter = ticketList.iterator();
			JSONArray ret = new JSONArray();
			while (ticketIter.hasNext()) {
				Ticket ticket = ticketIter.next();
				try {
					JSONObject ticketObj = toJSONTicket(ticket, s);
					ret.put(ticketObj);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			s.close();
			return ret.toString();
		}catch (Exception e) {
			t.rollback();
		}
		return null;
	}

	JSONObject toJSONTicket(Ticket ticket, Session s) throws JSONException{
		JSONObject ret = new JSONObject();
		ret.put(TicketField.TICKET_ID, ticket.getTicketId());
		ret.put(TicketField.TICKET_NAME, ticket.getTicketName());
		ret.put(TicketField.TICKET_CITY_ID, ticket.getTicketCity());
		int cid = ticket.getTicketCity();
		City city = (City) s.load(City.class, Integer.valueOf(cid));
		ret.put(TicketField.TICKET_CITY_NAME, city.getCityName());
		ret.put(TicketField.TICKET_PROVINCE_ID, city.getProvince()
				.getProvinceId());
		ret.put(TicketField.TICKET_PROVINCE_NAME, city.getProvince()
				.getProvinceName());

		ret.put(TicketField.TICKET_ADD, ticket.getTicketAdd());
		ret.put(TicketField.TICKET_DES, ticket.getTicketDes());
		ret.put(TicketField.TICKET_MANAGER_NAME, ticket.getTicketManagerName());
		ret.put(TicketField.TICKET_MANAGER_MOBILE, ticket.getTicketManagerTel());
		ret.put(TicketField.TICKET_LINKMAN_NAME, ticket.getTicketLinkmanName());
		ret.put(TicketField.TICKET_LINKMAN_MOBILE, ticket.getTicketLinkmanTel());
		ret.put(TicketField.TICKET_LINKMAN_QQ, ticket.getTicketLinkmanQq());
		ret.put(TicketField.TICKET_PAY_MODEL, ticket.getTicketPayMode());
		ret.put(TicketField.TICKET_UNPAY_MONEY, ticket.getTicketUnpaymoney());
		ret.put(TicketField.TICKET_UNPAY_DAY, ticket.getTicketUnpaydays());
		ret.put(TicketField.TICKET_BANK_HOLDER, ticket.getTicketBankHolder());
		ret.put(TicketField.TICKET_BANK_ACCOUNT, ticket.getTicketBankAccounts());
		ret.put(TicketField.TICKET_BANK_ADD, ticket.getTicketBankAdd());
		ret.put(TicketField.TICKET_SYMBIOSIS, ticket.getTicketSymbiosis());
		ret.put(TicketField.TICKET_START_DATE, ticket.getTicketBeginDate()
				.toString());
		ret.put(TicketField.TICKET_END_DATE, ticket.getTicketEndDate().toString());
		int workerId = ticket.getLastmodifyWorker();
		Worker worker = (Worker) s.load(Worker.class, Integer
				.valueOf(workerId));
		ret.put(TicketField.LASTMODIFY_WORKER_NAME, worker.getWorkerName());
		ret.put(TicketField.LASTMODIFY_TIME, ticket.getLastmodifyTime());

		return ret;
	}
	
	JSONObject toJSONStatus(Ticketstatus status) throws JSONException{
		JSONObject statusObj = new JSONObject();
		int aPrice = status.getTicketActualPrice();
		statusObj.put(TicketField.STATUS_ACTUAL_PRICE, aPrice);
		int bPrice = status.getTicketBasePrice();
		statusObj.put(TicketField.STATUS_BASE_PRICE, bPrice);
		int sPrice = status.getTicketSellPrice();
		statusObj.put(TicketField.STATUS_SELL_PRICE, sPrice);
		int sId = status.getTicketStatusId();
		statusObj.put(TicketField.STATUS_ID, sId);
		Date sDate = status.getTicketStatusStartDate();
		statusObj.put(TicketField.STATUS_START_DATE, sDate.toString());
		Date eDate = status.getTicketStatusEndDate();
		statusObj.put(TicketField.STATUS_END_DATE, eDate.toString());
		String type = status.getTicketStatusType();
		statusObj.put(TicketField.STATUS_TYPE, type);
		
		return statusObj;
	}
	
	private void fillTicket(Ticket ticket, JSONObject ticketObj) throws JSONException {
		String ticketName = ticketObj.getString(TicketField.TICKET_NAME);
		ticket.setTicketName(ticketName);
		int ticketCity = ticketObj.getInt(TicketField.TICKET_CITY_ID);
		ticket.setTicketCity(ticketCity);
		String ticketAdd = ticketObj.getString(TicketField.TICKET_ADD);
		ticket.setTicketAdd(ticketAdd);
		String ticketDes = ticketObj.optString(TicketField.TICKET_DES);
		ticket.setTicketDes(ticketDes);

		String ticketManagerName = ticketObj
				.optString(TicketField.TICKET_MANAGER_NAME);
		ticket.setTicketManagerName(ticketManagerName);
		String ticketManagerTel = ticketObj
				.optString(TicketField.TICKET_MANAGER_MOBILE);
		ticket.setTicketManagerTel(ticketManagerTel);
		String ticketLinkmanName = ticketObj
				.optString(TicketField.TICKET_LINKMAN_NAME);
		ticket.setTicketLinkmanName(ticketLinkmanName);
		String ticketLinkmanQq = ticketObj
				.optString(TicketField.TICKET_LINKMAN_QQ);
		ticket.setTicketLinkmanQq(ticketLinkmanQq);
		String ticketLinkmanTel = ticketObj
				.optString(TicketField.TICKET_LINKMAN_MOBILE);
		ticket.setTicketLinkmanTel(ticketLinkmanTel);

		String ticketPayMode = ticketObj
				.getString(TicketField.TICKET_PAY_MODEL);
		ticket.setTicketPayMode(ticketPayMode);
		int unpaymoney = ticketObj.optInt(TicketField.TICKET_UNPAY_MONEY);
		ticket.setTicketUnpaymoney(Integer.valueOf(unpaymoney));
		int unpaydays = ticketObj.optInt(TicketField.TICKET_UNPAY_DAY);
		ticket.setTicketUnpaydays(Integer.valueOf(unpaydays));
		String ticketBankHolder = ticketObj
				.optString(TicketField.TICKET_BANK_HOLDER);
		ticket.setTicketBankHolder(ticketBankHolder);
		String ticketBankAccounts = ticketObj
				.optString(TicketField.TICKET_BANK_ACCOUNT);
		ticket.setTicketBankAccounts(ticketBankAccounts);
		String ticketBankAdd = ticketObj.optString(TicketField.TICKET_BANK_ADD);
		ticket.setTicketBankAdd(ticketBankAdd);

		String ticketSymbiosis = ticketObj
				.getString(TicketField.TICKET_SYMBIOSIS);
		ticket.setTicketSymbiosis(ticketSymbiosis);
		String beginDate = ticketObj.getString(TicketField.TICKET_START_DATE);
		Date ticketBeginDate = java.sql.Date.valueOf(beginDate);
		ticket.setTicketBeginDate(ticketBeginDate);
		String endDate = ticketObj.getString(TicketField.TICKET_END_DATE);
		Date ticketEndDate = java.sql.Date.valueOf(endDate);
		ticket.setTicketEndDate(ticketEndDate);

		int lastmodifyWorker = ticketObj
				.getInt(TicketField.LASTMODIFY_WORKER);
		ticket.setLastmodifyWorker(lastmodifyWorker);
	}
	
	private void fillStatus(Ticketstatus status, JSONObject statusObj,
			Session session) throws JSONException {
		int aPrice = statusObj.optInt(TicketField.STATUS_ACTUAL_PRICE);
		status.setTicketActualPrice(aPrice);
		int bPrice = statusObj.optInt(TicketField.STATUS_BASE_PRICE);
		status.setTicketBasePrice(bPrice);
		int sPrice = statusObj.optInt(TicketField.STATUS_SELL_PRICE);
		status.setTicketSellPrice(sPrice);
		String type = statusObj.optString(TicketField.STATUS_TYPE);
		status.setTicketStatusType(type);
		
		String eDateStr = statusObj.optString(TicketField.STATUS_END_DATE);
		Date eDate = java.sql.Date.valueOf(eDateStr);
		status.setTicketStatusEndDate(eDate);
		String sDateStr = statusObj.optString(TicketField.STATUS_START_DATE);
		Date sDate = java.sql.Date.valueOf(sDateStr);
		status.setTicketStatusStartDate(sDate);
		
		int hId = statusObj.optInt(TicketField.TICKET_ID);
		Ticket ticket = (Ticket) session.load(Ticket.class, Integer.valueOf(hId));
		status.setTicket(ticket);
		
		int lastmodifyWorker = statusObj.getInt(TicketField.LASTMODIFY_WORKER);
		status.setLastmodifyWorker(lastmodifyWorker);
	}

	@SuppressWarnings("unchecked")
	@Override
	public String queryResult(String condition) {
		String hql = "from Ticketstatus status";
		try {
			JSONObject condObj = new JSONObject(condition);
			int cityId = condObj.optInt(TicketField.TICKET_CITY_ID);
			hql += " where status.ticket.ticketCity=" + cityId;
			String ticketName = condObj.optString(TicketField.TICKET_NAME);
			if (!ticketName.isEmpty()) {
				hql += " and status.ticket.ticketName like '%" + ticketName + "%'";
			}
			String add = condObj.optString(TicketField.TICKET_ADD);
			if (!add.isEmpty()) {
				hql += " and status.ticket.ticketAdd like '%" + add + "%'";
			}
			int lowPrice = condObj.optInt(TicketField.STATUS_LOW_PRICE);
			int highPrice = condObj.optInt(TicketField.STATUS_HIGH_PRICE);
			if(0 != highPrice){
				hql += " and status.ticketSellPrice between "+ lowPrice +" and "+highPrice;
			}else{
				hql += " and status.ticketSellPrice >="+ lowPrice;
			}
			String inDate = condObj.optString(TicketField.IN_DATE);
			hql += " and '"+ inDate +"' between status.ticketStatusStartDate and status.ticketStatusEndDate";
			
		} catch (JSONException e1) {
			e1.printStackTrace();
		}

		Session s = DBOper.openSession();
		Transaction t = s.beginTransaction();
		try{
			t.begin();
			Query query = s.createQuery(hql);
			//TODO:分页
			query.setFirstResult(0);
			query.setMaxResults(20);
			List<Ticketstatus> statusList = query.list();
			
			Iterator<Ticketstatus> statusIter = statusList.iterator();
			JSONArray ret = new JSONArray();
			while (statusIter.hasNext()) {
				Ticketstatus ticketstatus = statusIter.next();
				Ticket ticket = ticketstatus.getTicket();
				try {
					JSONObject ticketObj = toJSONTicket(ticket, s);
					JSONObject statusObj = toJSONStatus(ticketstatus);
					JSONObject tmp = new JSONObject();
					tmp.put(TicketField.TICKET, ticketObj);
					tmp.put(TicketField.STATUS, statusObj);
					ret.put(tmp);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			s.close();
			return ret.toString();
		}catch (Exception e) {
			t.rollback();
		}
		return null;
	}
}
